package com.simple.mipc.base;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Messenger;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.simple.mipc.handler.MessageHandler;

import java.util.Objects;

import lombok.Getter;

@Getter
public class MessengerService extends Service {

    private Messenger messenger;

    private static final int NOTIFICATION_ID = 1;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        if (Objects.isNull(messenger)) {
            messenger = new Messenger(new MessageHandler());
        }
        return messenger.getBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        NotificationChannel channel = new NotificationChannel("channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (manager != null) {
            manager.createNotificationChannel(channel);
        }

        Notification notification = new NotificationCompat.Builder(this, "channel_id")
                .setContentTitle("Messenger Server")
                .setContentText("跨进程通信测试......")
                .build();

        startForeground(NOTIFICATION_ID, notification);

        return START_STICKY;
    }
}
